<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="keyWord" placeholder="关键词"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="menus" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" label="序号" width="50">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="110">
      </el-table-column>
      <el-table-column prop="parent.name" label="上级菜单" width="120">
      </el-table-column>
      <el-table-column prop="url" label="访问URL" width="100">
      </el-table-column>
      <el-table-column prop="component" label="组件路径" width="200">
      </el-table-column>
      <el-table-column prop="icon" label="图标" width="120">
      </el-table-column>
      <el-table-column prop="intro" label="简介" width="100">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="200">
        <template scope="scope">
          <span v-if="scope.row.state" style="color: green">启动</span>
          <span v-else style="color: #ff0000">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize"
                     :currentPage="currentPage" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--保存界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-select v-model="saveForm.name" placeholder="请选择">
          <el-option
              v-for="item in managers"
              :key="item.value"
              :label="item.name"
              :value="item.name">
            <span style="float: left">{{ item.name }}</span>
          </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级菜单">
          <!--
            <el-cascader - 级联
              :options="deptTree" - 级联框中需要的数据【集合】
            回显机制：
              v-model="saveForm.parent"
                parent：[2,5]
          -->
          <el-cascader v-model="saveForm.parent"
                       :options="menuTree"
                       :props="{
                checkStrictly: true,
                label: 'name', //级联框显示那个属性的值
                value: 'id'    //回显时需要,回传值的时候也需要
              }" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="访问URL" prop="url">
          <el-input v-model="saveForm.url" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="saveForm.component" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="saveForm.icon" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="true" style="color: green">启动</el-radio>
            <el-radio class="radio" :label="false" style="color: red;">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {getMenuListPage, removeMenu, batchRemoveMenu, saveMenu, addMenu} from '../../api/api';

export default {
  data() {
    return {
      keyWord: "",
      title: "",
      menus: {
        parent:[]
      },
      totals: 0,
      pageSize: 10,
      currentPage: 1,
      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//保存界面是否显示
      saveLoading: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
      },
      //保存界面数据
      saveForm: {
        id: null,
        name: "",
        component: "",
        url: "",
        icon: "",
        index: null,
        parent_id: null,
        intro: "",
        state: true,
        parent:[],
      },
      managers: [],
      menuTree: [],
    }
  },
  methods: {
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getMenus();
    },
    keywordQuery() {
      // 防止查询后面页数的时候传过来的当前页不准确导致数据不显示
      this.currentPage = 1;
      this.getMenus();
    },
    getMenus() {
      let para = {
        keyWord: this.keyWord,
        currentPage: this.currentPage,	//当前页
        pageSize: this.pageSize,		//每页显示的条数
      };
      this.listLoading = true;			//显示加载框/忙等框
      this.$http.post("/menu", para).then(res => {
        //给totals赋值 - 计算分页栏
        this.totals = res.data.totals;
        //赋值分页数据 - 显示当前页的分页数据
        this.menus = res.data.data;
        //隐藏加载框/忙等框
        this.listLoading = false;
      }).catch(res => {
        this.$message.error('系统繁忙，请稍后重试!!!');
      });
    },
    // 删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {// 确认的反应
        this.listLoading = true;
        this.$http.delete("/menu/" + row.id).then(res => {
          // 如果后端返回ajaxResult成功，执行查询语句
          if (res.data.success) {
            let totalPage = this.totals % this.pageSize == 0 ? this.totals / this.pageSize
                : Math.ceil(this.totals / this.pageSize);
            if (this.currentPage > 1 && this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0) {
              this.currentPage = this.currentPage - 1;
              this.getMenus();
            } else {
              this.getMenus();
            }
          } else {
            this.$message.error("系统异常，请稍后再试[500]")
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("系统异常，请稍后再试[404]或者[400]")
        })
      }).catch(() => {// 取消后反应
      });
    },
    //显示保存界面
    handleSave: function (index, row) {
      this.title = "编辑";
      this.saveForm = Object.assign({}, row);
      console.log(this.saveForm)
      this.getMenuTree();
      this.getManager();
      this.saveForm.parent = [row.parentId];
      this.saveFormVisible = true;
    },
    //点击添加按钮弹出对话框
    handleAdd: function () {
      this.title = "新增";
      this.getManager();
      this.getMenuTree();
      this.saveForm = {
        id: null,
        name: "",
        component: "",
        url: "",
        icon: "",
        index: null,
        parentId: null,
        intro: "",
        state: true,
      };
      this.saveFormVisible = true;//显示对话框
    },
    //保存
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true;
            let paras = Object.assign({}, this.saveForm);
            //提交数据时上级部门数据格式做处理：[3,8] - {id:8}
            var arr = this.saveForm.parent; //[ 3, 8 ]
            if(arr){
              paras.parent = {id:arr[arr.length-1]}
              paras.parent_id = {id:arr[arr.length-1]}
            }
            this.$http.put("/menu",paras).then(res => {
              this.saveFormVisible = false;
              this.saveLoading = false;
              if(res.data.success){
                this.getMenus();
              }else{
                this.$message.error("操作失败【500】");
              }
            }).catch(res => {
              this.$message.error("系统错误【400,404】");
            })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {// 确认按钮触发
        this.$http.patch("/menu", ids).then(res => {
          if (res.data.success) {
            this.currentPage = 1;
            this.getMenus()
          } else {
            this.$message.error("系统繁忙,请稍后再试[500]")
          }
        }).catch(res => {
          this.$message.error("系统繁忙,请稍后再试[400 404]")
        })
      }).catch(() => {// 去掉按钮触发
      });
    },
    getManager() {
      this.$http.get("/menu").then(res => {
        this.managers = res.data;
      })
    },
    getMenuTree() {
      this.$http.get("/menu/menutree").then(res => {
        this.menuTree = res.data;
      })
    },
  },
  mounted() {
    this.getMenus();
  }
}

</script>

<style scoped>

</style>